package com.ykdl.member.kid.marketcard;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.http.Network;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.beans.Actor_InfoBean;
import com.ykdl.member.kid.beans.AvatarBean;
import com.ykdl.member.kid.beans.GetFileMate;
import com.ykdl.member.kid.beans.GetUser_ScoreBean;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.marketcard.CardPersonalInformationActivity.PutphotoTag;
import com.ykdl.member.kid.marketcard.CardPersonalInformationActivity.getDataTag;
import com.ykdl.member.kid.set.MybabyActivity;
import com.ykdl.member.kid.set.PredateSetActivity;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.CameraHelp;
import com.ykdl.member.kid.util.DateUtil;
import com.ykdl.member.kid.util.StringUtils;
import com.ykdl.member.views.MyWheelView;
import com.ykdl.member.views.MyWheelView.OnWheelViewDataChanger;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class PersonalDataActivity extends BaseScreen implements OnClickListener {

	private LinearLayout xingbie, birthday;
	private TextView whoes_birth, calculator;
	public static final String TAG = "CardPersonalInformationActivity";
	private LinearLayout layout_photomenu;
	private CameraHelp mSurveyCameraHelp;
	private ImageView headimg, cake_iv;
	private TextView gender, city_tv;
	private String picpath = "";
	final String[] genderaray = new String[] { "女宝宝", "男宝宝" };
	private MyWheelView location;
	private BitmapUtils bitmapUtil;
	private EditText nickname_et;
	TextView age_et, yucan_day;
	private MyWheelView wheel_time;
	private int gender_index;
	private BitmapUtils mBmpUtils;
	private ProgressDialog mProgressDialog;
	private boolean open = false;
	private boolean iopen = false;
	private long babybirthday;
	private static AccessTokenKeeper mTokenKeeper;
	private int state;
	private GetUser_ScoreBean bean;
	private String[] theTime;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTopTitle("编辑个人资料", 0, R.drawable.back_bg, new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		}, 0, 0, null, 0);
		setContent(R.layout.activity_personaldata);
		state = this.getIntent().getIntExtra("STATE", 0);
		xingbie = (LinearLayout) findViewById(R.id.xingbie);
		birthday = (LinearLayout) findViewById(R.id.birthday);
		cake_iv = (ImageView) findViewById(R.id.cake_iv);
		whoes_birth = (TextView) findViewById(R.id.whoes_birth);
		findViewById(R.id.submit).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				save();
			}
		});
		mSurveyCameraHelp = new CameraHelp(PersonalDataActivity.this);
		mSurveyCameraHelp.setOutputX(100);
		mSurveyCameraHelp.setOutputY(100);
		mSurveyCameraHelp.setAspectX(5);
		mSurveyCameraHelp.setAspectY(5);
		mSurveyCameraHelp.setmNeedzoom(true);
		bitmapUtil = new BitmapUtils(this);
		bitmapUtil.configDefaultLoadingImage(R.drawable.upload_head);
		bitmapUtil.configDefaultLoadFailedImage(R.drawable.upload_head);
		mTokenKeeper = new AccessTokenKeeper(this);
		initViews();

		wheel_time = (MyWheelView) findViewById(R.id.accountinfor_wheel_time);
		if (state == 1) {
			wheel_time.setTimeAfterNow(true);
		}
		wheel_time.setVisibility(View.INVISIBLE);
		wheel_time.setWheelView(MyWheelView.CALENDAR);
		wheel_time.findViewById(R.id.my_wheelview_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						open = false;
						wheel_time.setMyGone();
					}
				});
		wheel_time.setOnWheelViewDataChanger(new OnWheelViewDataChanger() {

			@Override
			public void updataByChanger(String data) {
				if (!open) {
					InputMethodManager mInputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
					mInputMethodManager.toggleSoftInput(0,
							InputMethodManager.RESULT_UNCHANGED_SHOWN);

				} else {
					String[] time = data.split(",");
					theTime = time;
					age_et.setText(time[0] + "年" + time[1] + "月" + time[2]
							+ "日     ");
					open = false;
					Date now = new Date();
					now.setYear(Integer.parseInt(time[0]) - 1900);
					now.setMonth(Integer.parseInt(time[1]) - 1);
					now.setDate(Integer.parseInt(time[2]));
					babybirthday = now.getTime() / 1000;
				}
			}
		});
		findViewById(R.id.edit_babyinfor).setOnClickListener(this);
		mBmpUtils = new BitmapUtils(this);
		bean = (GetUser_ScoreBean) this.getIntent().getSerializableExtra(
				"GetUser_ScoreBean");
		if (bean != null) {
			fillData(bean.getActor_info());
		} else {
			switchView();
		}
	}
	
	private void switchView() {
		switch (state) {// profile.getStatus()
		case 1: // 孕产期
			xingbie.setVisibility(View.GONE);
			whoes_birth.setText("预产期");
			cake_iv.setBackgroundResource(R.drawable.clock_icon);
			age_et.setHint("预产期是哪一天呢");
			calculator = (TextView) findViewById(R.id.calculator);
			calculator.setVisibility(View.VISIBLE);
			calculator.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);// 下划线
			calculator.setTextColor(Color.RED);
			calculator.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(mContext,
							PredateSetActivity.class);
					startActivityForResult(intent, 100);
				}
			});
			break;
		case 3: // 6岁以上
			xingbie.setVisibility(View.GONE);
			whoes_birth.setText("您的生日");
			break;
		case 2: // 0~6岁
			break;

		default:
			break;
		}
	}

	private void fillData(Actor_InfoBean profile) {
		if (profile == null) {
			return;
		}
		switch (state) {// profile.getStatus()
		case 1: // 孕产期
			xingbie.setVisibility(View.GONE);
			whoes_birth.setText("预产期");
			cake_iv.setBackgroundResource(R.drawable.clock_icon);
			if (!TextUtils.isEmpty(profile.getDue_date())) {
				babybirthday = Long.parseLong(profile.getDue_date());
				age_et.setText(DateUtil.getTopicDate(profile.getDue_date()));// 1459500288
																				// 2016
																				// 04
																				// 01
				theTime = DateUtil.getDateArray(profile.getDue_date());
			}
			age_et.setHint("预产期是哪一天呢");
			calculator = (TextView) findViewById(R.id.calculator);
			calculator.setVisibility(View.VISIBLE);
			calculator.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);// 下划线
			calculator.setTextColor(Color.RED);
			calculator.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(mContext,
							PredateSetActivity.class);
					startActivityForResult(intent, 100);
				}
			});
			break;
		case 3: // 6岁以上
			xingbie.setVisibility(View.GONE);
			whoes_birth.setText("您的生日");
			if (!TextUtils.isEmpty(profile.getUser_birthday())) {
				babybirthday = Long.parseLong(profile.getUser_birthday());
				age_et.setText(DateUtil.getTopicDate(profile.getUser_birthday()));
				theTime = DateUtil.getDateArray(profile.getUser_birthday());
			}
			break;
		case 2: // 0~6岁
			if (!TextUtils.isEmpty(profile.getBirthday())) {
				babybirthday = Long.parseLong(profile.getBirthday());
				age_et.setText(DateUtil.getTopicDate(profile.getBirthday()));
				theTime = DateUtil.getDateArray(profile.getBirthday());
			}
			if ("1".equals(profile.getGender())) {
				gender.setText(genderaray[1]);
				gender_index = 1;
			} else {
				gender.setText(genderaray[0]);
				gender_index = 0;
			}
			break;

		default:
			break;
		}
		if (null != profile.getAvatar_info()) {
			bitmapUtil.display(headimg, profile.getAvatar_info().getFile_url());
		}
		nickname_et.setText(profile.getDisplay_name());
		city_tv.setText(profile.getAddress());
	}

	private void initViews() {
		// TODO Auto-generated method stub
		location = (MyWheelView) findViewById(R.id.select_location_layout);
		headimg = (ImageView) findViewById(R.id.iask_head_btn);
		gender = (TextView) findViewById(R.id.iask_gender); // 宝宝性别
		nickname_et = ((EditText) findViewById(R.id.iask_nick));
		city_tv = ((TextView) findViewById(R.id.iask_city));
		city_tv.setOnClickListener(this);
		age_et = ((TextView) findViewById(R.id.iask_age)); // 宝宝生日
		age_et.setOnClickListener(this);
		findViewById(R.id.iask_gender).setOnClickListener(this);

		findViewById(R.id.iask_account_head).setOnClickListener(this);
		layout_photomenu = (LinearLayout) this.findViewById(R.id.iask_selphoto);
		layout_photomenu.setFocusable(true);
		layout_photomenu.setFocusableInTouchMode(true);
		findViewById(R.id.photograph).setOnClickListener(  
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						mSurveyCameraHelp.selectImageFromCamera();
						layout_photomenu.setVisibility(View.GONE);

					}
				});
		findViewById(R.id.album).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mSurveyCameraHelp.selectImageFromLocal();
				layout_photomenu.setVisibility(View.GONE);
			}
		});
		findViewById(R.id.cencel).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						layout_photomenu.setVisibility(View.GONE);
					}
				});
		location.setWheelView(MyWheelView.CHINA);
		location.setVisibility(View.INVISIBLE);
		location.findViewById(R.id.my_wheelview_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						iopen = false;
						location.setMyGone();
					}
				});
		location.setOnWheelViewDataChanger(new OnWheelViewDataChanger() {
			@Override
			public void updataByChanger(String data) {
				if (!iopen) {
					InputMethodManager mInputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
					mInputMethodManager.toggleSoftInput(0,
							InputMethodManager.RESULT_UNCHANGED_SHOWN);

				} else {
					QLog.debug("data", data);
					String[] datas = data.split("&#&");
					String[] contents = datas[0].split(",");
					String result = "";
					for (int i = 0; i < contents.length; i++) {
						if (!"".equals(result)) {
							result += "，";
						}
						result += contents[i];
					}
					city_tv.setText(result);
					iopen = false;
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.edit_babyinfor:
			// 宝宝设置页面
			go(MybabyActivity.class);
			break;
		case R.id.iask_account_head:
			layout_photomenu.setVisibility(View.VISIBLE);
			break;
		case R.id.iask_age:
			wheel_time.setVisibility(View.VISIBLE);
			open = true;
			((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(PersonalDataActivity.this
							.getCurrentFocus().getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
			wheel_time.setInVisible(true);
			wheel_time.setMyVisible();
			break;
		case R.id.iask_gender: // 宝宝性别
			String tt = gender.getText().toString();
			AlertDialog alertDialog = new AlertDialog.Builder(
					PersonalDataActivity.this).setSingleChoiceItems(genderaray,
					gender_index, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							gender.setText(genderaray[which]);
							gender_index = which;
							dialog.cancel();
						}
					}).create();
			alertDialog.show();
			break;
		case R.id.iask_city:
			iopen = true;
			location.setVisibility(View.VISIBLE);
			((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(PersonalDataActivity.this
							.getCurrentFocus().getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
			location.setInVisible(true);
			location.setMyVisible();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (/* CameraHelp.SURVEY_CAMERA_WITH_DATA == requestCode &&& */resultCode == RESULT_OK) {
			try {
				picpath = mSurveyCameraHelp.setPicture(requestCode, resultCode,
						data);
				File file = new File(picpath);
				putphoto(file);
				headimg.setImageURI(Uri.parse(picpath));
				headimg.setBackgroundDrawable(null);
			} catch (Throwable ee) {
				QLog.debug(TAG, "内存不足===!!!!!!1");
				Toast.makeText(this, "内存不足", Toast.LENGTH_SHORT).show();
				picpath = "";
			}
			QLog.debug(TAG, "picpath===" + picpath);
			
	  //***********************************************************************
//			picpath = mSurveyCameraHelp.setPicture(requestCode, resultCode,
//					data);
//			Intent intent=new Intent(mContext, CutPicActivity.class);
//			intent.putExtra("Path", picpath);
//			startActivityForResult(intent, 0);
		}
		if (requestCode == CameraHelp.SURVEY_PHOTO_ZOOM) {
		}
//		if(resultCode==101){
//			if(CutPicActivity.bitmap!=null){
//				File file = new File(CutPicActivity.filePath);
//				putphoto(file);
//				headimg.setImageBitmap(CutPicActivity.bitmap);
//			}else{
//				Toast.makeText(mContext, "截取失败", 0).show();
//			}
//			
//		}
		/**
		 * 处理预产期
		 */
		if (resultCode == 100) {
			String predate = data.getStringExtra("PREDATE");
			String[] time = predate.split(",");
			theTime = time;
			age_et.setText(time[0] + "年" + time[1] + "月" + time[2] + "日     ");
			open = false;
			Date now = new Date();
			now.setYear(Integer.parseInt(time[0]) - 1900);
			now.setMonth(Integer.parseInt(time[1]) - 1);
			now.setDate(Integer.parseInt(time[2]));
			babybirthday = now.getTime() / 1000;
		}
	}


	@Override
	public void onBackPressed() {
		if (layout_photomenu.getVisibility() == View.VISIBLE
				|| wheel_time.getMyVisibility() == View.VISIBLE) {
		}
		super.onBackPressed();
	}

	private void save() {
		String name = nickname_et.getText().toString().trim();
		if (StringUtils.chineseLength(name) < 3
				|| StringUtils.chineseLength(name) > 24) {
			Toast.makeText(this, "用户昵称应在3-24个字符", 1).show();
			return;
		}
		String region = city_tv.getText().toString();
		if (TextUtils.isEmpty(region)) {
			Toast.makeText(this, "输入地区信息", 1).show();
			return;
		}
		String strDate = age_et.getText().toString();
		if(state == 3){
			if (TextUtils.isEmpty(strDate)) {
				Toast.makeText(this, "请选择出生日期", 1).show();
				return;
			}
		}
		if (state == 2) {
			if (TextUtils.isEmpty(strDate)) {
				Toast.makeText(this, "请选择宝宝生日", 1).show();
				return;
			}
//			int days = compairTime(theTime);
			int years =yearsOfTwo(theTime);
			if (years>6 || years<0) {// 限制0~6岁的孩子出生日期在一定的时间段内（不能超过6年前）  days < -2192 || days > 0
				Toast.makeText(mContext, "请输入正确的出生日期哦", 0).show();
				return;
			}
		}
		if (state == 1) {
			if (TextUtils.isEmpty(strDate)) {
				Toast.makeText(this, "请选择预产期", 1).show();
				return;
			}
			int days = compairTime(theTime) + 1;
			if (days > 280 || isBeforeToday(theTime)) {
				Toast.makeText(mContext, "请输入正确的预产期哦", 0).show();
				return;
			}

		}
		showProgress("加载中。。。");
		Network.getInstance().newperfectProfile(name, babybirthday, region,
				gender_index, new ProfileTag(), state);
	}

	public void putphoto(File file) {
		String pageurl = KidConfig.UPDATE_AVATAR;
		HttpBaseRequest request = Wxxr.getInstance()
				.uploadAvatar(pageurl, file);
		TaskManager.startHttpRequest(request, new PutphotoTag(),
				AvatarBean.class);
	}

	class PutphotoTag implements ITag<AvatarBean> {

		@Override
		public void refreshUI(AvatarBean t, DataState ds) {
			// TODO Auto-generated method stub
			if (t != null) {
				// TODO 完善资料接口还没有file_id
				AvatarBean bean = (AvatarBean) t;
				if (bean.getError() == null) {
					Toast.makeText(PersonalDataActivity.this, "头像上传成功", 1)
							.show();
				} else {
					Toast.makeText(PersonalDataActivity.this, "头像上传失败", 1)
							.show();
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			if (parseError != null
					&& !TextUtils.isEmpty(parseError.getErrMsg())) {
				Toast.makeText(PersonalDataActivity.this,
						parseError.getErrMsg(), Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(PersonalDataActivity.this, "头像上传失败", 1).show();
			}
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}

	}

	private class ProfileTag implements ITag<GetUser_ScoreBean> {

		@Override
		public void refreshUI(GetUser_ScoreBean t, DataState ds) {
			if (mProgressDialog != null)
				mProgressDialog.dismiss();
			finishProgress();
			if (t instanceof GetUser_ScoreBean) {
				GetUser_ScoreBean bean = (GetUser_ScoreBean) t;
				if (null == bean.getError()) {
					Toast.makeText(PersonalDataActivity.this, "保存成功", 1).show();
				} else {
					Toast.makeText(PersonalDataActivity.this,
							"保存失败," + bean.getDesc(), 1).show();
				}

			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			if (mProgressDialog != null)
				mProgressDialog.dismiss();
			Toast.makeText(PersonalDataActivity.this, "个人详细信息设置失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
	}
	
	
}
